/**
 * 主场景
 */

export default class MainScene extends Phaser.Scene {
    constructor() {
        super({key: "MainScene"});
    }

    preload() {
        this.score = 0;
        this.round = 1;
        this.life = 3;
        this.baddie_speed = 20;
        this.isInRed = false;
    }

    create() {
        this.add.sprite(400, 300, 'example01', 'sky.webp');
        this.platforms = this.physics.add.staticGroup();
        this.platforms.create(400, 568, 'example01', `platform.${window.imageSuffix}`).setScale(2).refreshBody();
        this.platforms.create(600, 400, 'example01', `platform.${window.imageSuffix}`);
        this.platforms.create(50, 250, 'example01', `platform.${window.imageSuffix}`);
        this.platforms.create(750, 220, 'example01', `platform.${window.imageSuffix}`);
        this.player = this.physics.add.sprite(100, 450, "dude").setBounceX(0.2).setCollideWorldBounds(true);
        this.physics.add.collider(this.player, this.platforms);
        this.cursors = this.input.keyboard.createCursorKeys()
        this.stars = this.physics.add.group({
            key: "example01",
            frame: `star.${window.imageSuffix}`,
            repeat: 11,
            setXY: {x: 12, y: 0, stepX: 70}
        })

        this.stars.children.iterate(child => {
            child.setBounceY(Phaser.Math.FloatBetween(0.4, 0.8))
        })
        this.physics.add.collider(this.stars, this.platforms);
        this.physics.add.overlap(this.player, this.stars, handleStar, null, this);
        this.scoreText = this.add.text(16, 16, "Score: 0", {
            color: "#ffffff",
            fontFamily: "宋体",
            fontSize: "16px"
        })

        this.bombs = this.physics.add.group()
        this.physics.add.collider(this.bombs, this.platforms);
        this.physics.add.collider(this.bombs, this.bombs);
        this.physics.add.overlap(this.player, this.bombs, handleBomb, null, this);

        this.over = this.tweens.add({
            targets: this.player,
            y: '+=600',
            duration: 5000,
            paused: true,
            ease: 'Bounce.easeOut'
        });

        this.lifeGroup = this.physics.add.staticGroup();
        this.physics.add.overlap(this.player, this.lifeGroup, handleLife, null, this);
        this.lifeText = this.add.text(16, 48, "Life: 3", {
            color: "#ffffff",
            fontFamily: "宋体",
            fontSize: "16px"
        })
        this.diamondGroup = this.physics.add.staticGroup();
        this.physics.add.overlap(this.player, this.diamondGroup, handleDiamond, null, this);

        this.baddie = this.physics.add.sprite(50, 50, "baddie").setBounceX(0.1).setCollideWorldBounds(true);
        this.physics.add.collider(this.baddie, this.platforms);
        this.physics.add.overlap(this.player, this.baddie, handleBaddie, null, this);
    }

    update() {

        if (this.cursors.left.isDown) {
            this.player.setVelocityX(-160);
            this.player.anims.play("left", true)
        } else if (this.cursors.right.isDown) {
            this.player.setVelocityX(160);
            this.player.anims.play("right", true)
        } else {
            this.player.setVelocityX(0);
            this.player.anims.play('turn');
        }
        if (this.cursors.up.isDown && this.player.body.touching.down) {
            this.player.setVelocityY(-500);
        }

        if (this.baddie.x <= 50) {
            this.baddie_speed = 20
            this.baddie.anims.play("baddie_right", true)
        } else if (this.baddie.x >= 750) {
            this.baddie_speed = -20
            this.baddie.anims.play("baddie_left", true)
        }
        this.baddie.setVelocityX(this.baddie_speed);
    }
}

function handleStar(player, star) {
    star.disableBody(true, true);
    this.score += 10;
    this.scoreText.setText(`Score: ${this.score}`);
    if (this.stars.countActive(true) === 0) {
        this.stars.children.iterate(child => {
            child.enableBody(true, child.x, 0, true, true)
        })

        const x = player.x < 400 ? Phaser.Math.Between(400, 800) : Phaser.Math.Between(0, 400);
        this.bombs.create(x, 0, 'example01', `bomb.${window.imageSuffix}`).setBounce(1).setCollideWorldBounds(true).setVelocity(Phaser.Math.Between(-200, 200), Phaser.Math.Between(10, 30));
        const life_x = player.x < 400 ? Phaser.Math.Between(400, 700) : Phaser.Math.Between(50, 350);
        const life_y = player.y < 300 ? Phaser.Math.Between(285, 365) : Phaser.Math.Between(50, 180);
        this.round++;
        if (this.round % 3 === 0) {
            this.lifeGroup.create(life_x, life_y, 'example01', `firstaid.${window.imageSuffix}`);
        }
        const diamond_x = player.x > 400 ? Phaser.Math.Between(400, 700) : Phaser.Math.Between(50, 350);
        const diamond_y = player.y > 300 ? Phaser.Math.Between(285, 365) : Phaser.Math.Between(50, 180);
        if (this.round % 2 === 0) {
            this.diamondGroup.create(diamond_x, diamond_y, 'example01', `diamond.${window.imageSuffix}`);
        }
    }
}

function handleBomb(player, bomb) {
    this.life--;
    if (this.life <= 0 || this.score <= 0) {
        this.physics.pause()
        player.setTint(0xff0000);
        player.anims.play("turn");
        this.over.play();

        setTimeout(() => {
            this.scene.start('EndScene', this.score);
        }, 5000)
    } else {
        player.setTint(0xff0000);
        bomb.disableBody(true, true);
        setTimeout(() => {
            player.clearTint();
        }, 1000)
    }
    this.lifeText.setText(`Life: ${this.life}`);
}

function handleLife(player, life) {
    life.disableBody(true, true);
    this.life++;
    this.lifeText.setText(`Life: ${this.life}`);
}

function handleDiamond(player, diamond) {
    diamond.disableBody(true, true);
    this.score += 100;
    this.scoreText.setText(`Score: ${this.score}`);
}

function handleBaddie(player, baddie) {
    if (!this.isInRed) {
        if (this.score - 30 > 0) {
            this.isInRed = true
            player.setTint(0xff0000);
            this.score -= 30;
            this.scoreText.setText(`Score: ${this.score}`);
            setTimeout(() => {
                this.isInRed = false
                player.clearTint();
            }, 3000)
        } else {
            this.physics.pause()
            this.score -= 30;
            this.scoreText.setText(`Score: ${this.score}`);
            player.setTint(0xff0000);
            player.anims.play("turn");
            this.over.play();

            setTimeout(() => {
                this.scene.start('EndScene', this.score);
            }, 5000)
        }
    }
}